package com.tinem.platform.web.auth.login.code;

import cn.hutool.core.lang.Validator;
import com.tinem.platform.client.security.VerificationCodeClient;
import com.tinem.platform.module.pojo.vo.error.UserException;
import com.tinem.platform.module.pojo.vo.security.verification.code.VerificationReq;
import com.tinem.platform.module.starter.sdk.MessageCode;
import com.tinem.platform.web.auth.login.LoginService;
import com.tinem.platform.web.auth.page.LoginUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className SmsCodeAuthenticationProvider
 * @description TODO
 * @site 
 * @company 
 * @create 2020-10-01 17:16
 */
@Component
public class CodeAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private LoginService loginService;
    @Autowired
    VerificationCodeClient verificationCodeClient;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        CodeAuthenticationToken authenticationToken = (CodeAuthenticationToken) authentication;
        String to = (String) authenticationToken.getPrincipal();
        if(!verificationCodeClient.verification(new VerificationReq(authenticationToken.getTo(),authenticationToken.getCodeId(),authenticationToken.getCode())).isSuccess()){
            throw new UserException(MessageCode.ERROR_PLATFORM_CLOUD_WEB_AUTH_CODE);
        }
        String userId;
        if(Validator.isEmail(to)){
            userId = loginService.findUserByEmail(to);
        }else if(Validator.isMobile(to)){
            userId = loginService.findUserByMobile(authenticationToken.getCountryMobileCode(),to);
        }else{
            throw new UserException(MessageCode.ERROR_PLATFORM_CLOUD_WEB_AUTH_CODE_TO);
        }
        LoginUserInfo loginUserInfo = loginService.getLoginUser(userId);
        CodeAuthenticationToken codeAuthenticationToken = new CodeAuthenticationToken(loginUserInfo,loginUserInfo.getAuthorities());
        codeAuthenticationToken.setDetails(authenticationToken.getDetails());
        return codeAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
